home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / Apply.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  924 b   |  43 lines

  1. //: C20:Apply.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Using basic iterators
  7. #include <iostream>
  8. #include <vector>
  9. #include <iterator>
  10. using namespace std;
  11.  
  12. template<class Cont, class PtrMemFun>
  13. void apply(Cont& c, PtrMemFun f) {
  14.   typename Cont::iterator it = c.begin();
  15.   while(it != c.end()) {
  16.     (it->*f)(); // Compact form
  17.     ((*it).*f)(); // Alternate form
  18.     it++;
  19.   }
  20. }
  21.  
  22. class Z {
  23.   int i;
  24. public:
  25.   Z(int ii) : i(ii) {}
  26.   void g() { i++; }
  27.   friend ostream& 
  28.   operator<<(ostream& os, const Z& z) {
  29.     return os << z.i;
  30.   }
  31. };
  32.  
  33. int main() {
  34.   ostream_iterator<Z> out(cout, " ");
  35.   vector<Z> vz;
  36.   for(int i = 0; i < 10; i++)
  37.     vz.push_back(Z(i));
  38.   copy(vz.begin(), vz.end(), out);
  39.   cout << endl;
  40.   apply(vz, &Z::g);
  41.   copy(vz.begin(), vz.end(), out);
  42. } ///:~
  43.